<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\model\dealer;

use app\common\model\dealer\Apply as ApplyModel;
use app\common\enum\dealer\apply\ApplyStatus as ApplyStatusEnum;

/**
 * 分销商入驻申请模型
 * Class Apply
 * @package app\store\model\dealer
 */
class Apply extends ApplyModel
{
    /**
     * 获取分销商申请列表
     * @param string $search
     * @return \think\Paginator
     */
    public function getList(string $search = ''): \think\Paginator
    {
        // 检索查询条件
        $filter = [];
        if (!empty($search)) {
            $filter[] = ['user.nick_name|apply.real_name|apply.mobile', 'like', "%{$search}%"];
        }
        // 查询列表记录
        return $this->alias('apply')
            ->field(['apply.*'])
            ->with(['referee.avatar', 'user.avatar'])
            ->where($filter)
            ->join('user', 'user.user_id = apply.user_id')
            ->order(['apply.create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 分销商入驻审核
     * @param array $data
     * @return bool
     */
    public function submit(array $data): bool
    {
        if ($data['apply_status'] == ApplyStatusEnum::REJECT && empty($data['reject_reason'])) {
            $this->error = '请填写驳回原因';
            return false;
        }
        $this->transaction(function () use ($data) {
            if ($data['apply_status'] == ApplyStatusEnum::PASS) {
                // 新增分销商用户
                User::add($this['user_id'], [
                    'real_name' => $this['real_name'],
                    'mobile' => $this['mobile'],
                    'referee_id' => $this['referee_id'],
                ]);
            }
            // 更新申请记录
            $data['audit_time'] = time();
            $this->save($data);
        });
        return true;
    }
}